﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using JiZiYan.Models;
using System.Web.Mvc;

namespace JiZiYan.Controllers
{
    /// <summary>
    /// 添加管理员
    /// </summary>
    public class AddAdminController : Controller
    {
       
        /// <summary>
        /// 添加页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            using (JiZiYanEntities2 db = new JiZiYanEntities2())
            {
                var arr = db.Roles.Where(x => true).ToList();
                ViewBag.RolesName = arr;
            }
            return View();
        }
        /// <summary>
        /// 添加方法
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Add(Addadmin data)
        {
            JiZiYanEntities2 db = new JiZiYanEntities2();
            Users u = new Users();
            u.Id = Guid.NewGuid();
            u.LoginName = data.LoginName;
            var repname = db.Users.SingleOrDefault(x => x.LoginName == u.LoginName);
            if (repname != null)
            {
                return Json(new { success = false, msg = "该用户名已存在" });                
            }
            u.Password = data.Password;
            u.ProtectEMail = data.ProtectEMail;
            u.ProtectMTel = data.ProtectMTel;
            u.CreateTime= DateTime.Now;
            u.IsLockout = bool.Parse("False");
            db.Users.Add(u);
            int count = db.SaveChanges();
            if (count > 0)
            {
                UserRoles s = new UserRoles();
                s.Id = Guid.NewGuid();
                s.RoleId = data.RoleId;
                s.UserId = u.Id;
                db.UserRoles.Add(s);
                int counts = db.SaveChanges();
                if (counts > 0)
                {
                    return Json(new { success = true, msg = "添加成功" });
                }
                else
                {
                    return Json(new { success = false, msg = "添加失败" });
                }
            }
            else
            {
                return Json(new { success = false, msg = "添加失败" });
            }           
        }
        

    }
}